import cv2

cap=cv2.VideoCapture(r'C:\Users\ASUS\Desktop\1.avi')
fgbg=cv2.createBackgroundSubtractorMOG2()#创建混合高斯模型
thresh=200
color=((0.205,205),(154,250,0),(34,34,178),(211,0,148),(255,118,72),(137,137,139))#矩形颜色


#读取视频
while True:
    ret,frame=cap.read()
    if not ret:
        break

    fgmask = fgbg.apply(frame)#读取前景掩膜
    _,fgmask=cv2.threshold(fgmask,10,0xff,cv2.THRESH_BINARY)#去噪
    bgImage=fgbg.getBackgroundImage()#寻找背景
    _,cnts,_=cv2.findContours(fgmask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#寻找前景

    count=0
    for c in cnts:
        area=cv2.contourArea(c)
        if(area<thresh):
            continue
        count+=1
        print("{}-prospect:{}".format(count,area))#显示面积
        x,y,w,h=cv2.boundingRect(c)
        print("X:{},Y:{}".format(x,y))  # 显示坐标
        cv2.rectangle(frame,(x,y),(x+w,y+h),color[count%6],1)#原图花不同颜色的框
        cv2.rectangle(fgmask,(x,y),(x + w, y + h),(0xff,0xff,0xff),1)#黑白前景上画框
        y=10 if y<10 else y
        cv2.putText(frame, str(count), (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.4, (0, 0xff, 0),1)  # 在前景框左上角编号
        cv2.putText(frame, str((x,y)), (x+10, y), cv2.FONT_HERSHEY_COMPLEX, 0.4, (0, 0xff, 0), 1)  # 在前景框左上角编号
    cv2.putText(frame,"count:", (5, 20), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 0xff, 0),1)  # 显示总数
    cv2.putText(frame, str(count), (75,20), cv2.FONT_HERSHEY_COMPLEX, 0.6, (0, 0xff, 0),1)
    print('----------------------------------------')

    print('共检测到',count,'个目标','\n')
    cv2.imshow('frame',frame)
    cv2.imshow('background',bgImage)
    cv2.imshow('fgmask',fgmask)

    key=cv2.waitKey(30)
    if key==27:
        break


cap.release()
cv2.destroyAllWindows()